package com.mnsq.category.service.impl;

import com.mnsq.category.bean.condition.CategoryCondition;
import com.mnsq.category.bean.entity.Category;
import com.mnsq.category.dao.CategoryRepository;
import com.mnsq.category.service.CategoryService;
import com.mnsq.common.tools.jpa.JpaExample;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryRepository categoryRepository;

    @Override
    public List<Category> queryPageByCondition(CategoryCondition categoryCondition) {
        if (categoryCondition.isEmpty()) {
            return categoryRepository.findAll(PageRequest.of(categoryCondition.getPageNum(), categoryCondition.getPageSize())).getContent();
        }
        return categoryRepository.findAll(
                JpaExample.getInstance().getExample(categoryCondition, Category.class),
                PageRequest.of(categoryCondition.getPageNum(), categoryCondition.getPageSize())).getContent();
    }

    @Override
    public List<Category> queryList(CategoryCondition categoryCondition) {
        if (StringUtils.isBlank(categoryCondition.getStr())) {
            return Collections.emptyList();
        }
        return categoryRepository.findAll(JpaExample.getInstance().getExample(categoryCondition, Category.class));
    }

    @Override
    public void add(List<Category> list) {
        for (Category category : list) {
            categoryRepository.saveAndFlush(category);
        }
    }

    @Override
    public void del(List<Category> list) {
        for (Category category : list) {
            categoryRepository.delete(category);
        }
    }
}
